package com.demo.apparel.service.uniapp.Impl;

import com.demo.apparel.dto.uniapp.WxFeedbackDTO;
import com.demo.apparel.dto.uniapp.WxFeedbackSubmitDTO;
import com.demo.apparel.entity.AdminInfo;
import com.demo.apparel.entity.Feedback;
import com.demo.apparel.entity.FeedbackImg;
import com.demo.apparel.mapper.uniapp.WxAdminMapper;
import com.demo.apparel.mapper.uniapp.WxFeedbackImgMapper;
import com.demo.apparel.mapper.uniapp.WxFeedbackMapper;
import com.demo.apparel.service.uniapp.WxFeedbackService;
import com.demo.apparel.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Service
@RequiredArgsConstructor
public class WxFeedbackServiceImpl implements WxFeedbackService {

    @Autowired
    private WxFeedbackImgMapper wxFeedbackImgMapper;

    @Autowired
    private WxFeedbackMapper wxFeedbackMapper;

    @Autowired
    private WxAdminMapper wxAdminMapper;

    private final String uploadDir = System.getProperty("user.dir") + "/feedback/";
    private final String urlPrefix = "/static/feedback/";

    /**
     *
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, String>> feedbackImageAndSave(List<MultipartFile> files, String userId) {
        if (files == null || files.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        List<Map<String, String>> resultList = new ArrayList<>();

        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename != null && originalFilename.contains(".")
                    ? originalFilename.substring(originalFilename.lastIndexOf("."))
                    : "";

            String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
            String imageUrl = urlPrefix + filename;
            String id = UUID.randomUUID().toString().replace("-", "");

            try {
                file.transferTo(new File(dir, filename));
                FeedbackImg img = new FeedbackImg();
                img.setId(id);
                img.setUserId(userId);
                img.setImgUrl(imageUrl);
                img.setCreatedTime(LocalDateTime.now());
                wxFeedbackImgMapper.insert(img);
                Map<String, String> map = new HashMap<>();
                map.put("id", id);
                map.put("imgUrl", imageUrl);
                resultList.add(map);
            } catch (IOException e) {
                throw new RuntimeException("图片上传失败", e);
            }
        }

        return resultList;
    }


    /**
     *
     * @param userId
     * @param dto
     */


    @Override
    @Transactional
    public void submitFeedback(WxFeedbackSubmitDTO dto, String userId) {
        // 1. 插入反馈主表
        Feedback feedback = new Feedback();
        String feedbackId = UUID.randomUUID().toString().replace("-", "");
        feedback.setId(feedbackId);
        feedback.setUserId(userId);
        feedback.setContent(dto.getContent());
        feedback.setContact(dto.getContact());
        feedback.setCreatedTime(LocalDateTime.now());
        feedback.setUpdatedTime(LocalDateTime.now());
        feedback.setStatus(0); // 默认未处理
        wxFeedbackMapper.insert(feedback);

        // 2. 关联图片：使用前端传来的图片ID，更新反馈ID字段完成绑定
        List<String> imageIds = dto.getImageIds();
        if (imageIds != null && !imageIds.isEmpty()) {
            for (String imgId : imageIds) {
                wxFeedbackImgMapper.updateFeedbackIdById(imgId, feedbackId);
            }
        }
    }


    /**
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageVO<WxFeedbackDTO> getUserFeedbackPage(String userId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        List<WxFeedbackDTO> feedbackList = wxFeedbackMapper.selectByUserId(userId, offset, pageSize);
        long total = wxFeedbackMapper.countByUserId(userId);

        for (WxFeedbackDTO dto : feedbackList) {
            List<FeedbackImg> imgs = wxFeedbackImgMapper.selectByFeedbackId(dto.getId());
            List<String> imgUrls = imgs.stream().map(FeedbackImg::getImgUrl).toList();
            dto.setImageUrls(imgUrls);
        }

        return new PageVO<>(feedbackList, total, pageNum, pageSize);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public WxFeedbackDTO getFeedbackDetail(String id) {
        WxFeedbackDTO dto = wxFeedbackMapper.selectById(id);
        if (dto == null) {
            throw new RuntimeException("反馈不存在");
        }

        List<FeedbackImg> imgs = wxFeedbackImgMapper.selectByFeedbackId(id);
        List<String> urls = imgs.stream().map(FeedbackImg::getImgUrl).toList();
        dto.setImageUrls(urls);
        // 查询管理员信息（如果 admin_id 不为空）
        if (dto.getAdminId() != null && !dto.getAdminId().isEmpty()) {
            AdminInfo adminInfo = wxAdminMapper.selectAdminInfoById(dto.getAdminId());
            if (adminInfo != null) {
                dto.setAdminNickname(adminInfo.getNickname());
                dto.setAdminAvatar(adminInfo.getAvatar());
            }
        }


        return dto;
    }

}